#include <iostream>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>

using namespace std;
#define SERVER_IP "127.0.0.1"
#define PORT 8888
#define BUFFER_SIZE 1024

int main()
{
    int client_fd;
    struct sockaddr_in server_addr;
    char buffer[BUFFER_SIZE];

    // 创建套接字
    if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket error");
        exit(1);
    }
    // 设置服务器地址结构
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    // 连接到服务器
    if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        perror("connect error");
        exit(1);
    }
    cout << "成功连接到服务器" << endl;

    // 向服务器发送数据
    const char *message = "你好 服务器（来自客户端）";
    send(client_fd, message, strlen(message), 0);
    // 接收数据
    int n = recv(client_fd, buffer, BUFFER_SIZE, 0);
    if (n <= 0)
    {
        perror("recv failed");
        exit(1);
    }
    buffer[n] = '\0';
    cout << "服务器发来" << buffer << endl;
    // 关闭套接字
    close(client_fd);
    return 0;
}